THREAD_PROFILE_MAP = {}

class CoachAPIView(APIView):
    def post(self, request, *args, **kwargs):
        user_input = request.data.get('user_input', '')
        user_profile = request.data.get('user_profile', {})
        thread_id = request.data.get('thread_id', 'default_thread')

        # 如果有 user_profile，則保存到全局映射
        if user_profile and any(v not in [None, '', '--'] for v in user_profile.values()):
            THREAD_PROFILE_MAP[thread_id] = user_profile

        # 問答時自動帶入該 thread_id 的 user_profile
        profile_for_this_thread = THREAD_PROFILE_MAP.get(thread_id, {})

        try:
            initial_state = get_initial_state(user_input, profile_for_this_thread)
            result = coach_chain.invoke(
                initial_state,
                config={"configurable": {"thread_id": thread_id}}
            )
            return Response({
                "user_input": user_input,
                "response": result["response"],
                "sources": result["source_docs"],
                "conversation_history": result["chat_history"],
                "thread_id": thread_id
            })
        except Exception as e:
            return Response({"error": f"处理错误: {str(e)}"}, status=500) 